package com.marketing.tenant.controller;

import com.marketing.common.Result;
import com.marketing.tenant.annotation.RequirePermission;
import com.marketing.tenant.dto.CreateTenantRequest;
import com.marketing.tenant.dto.UpdateTenantRequest;
import com.marketing.tenant.entity.Tenant;
import com.marketing.tenant.service.TenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 租户管理控制器
 */
@RestController
@RequestMapping("/api/tenants")
@Tag(name = "租户管理", description = "租户注册、信息维护、状态管理等操作")
@SecurityRequirement(name = "Bearer Authentication")
public class TenantController {

    private static final Logger log = LoggerFactory.getLogger(TenantController.class);

    @Autowired
    private TenantService tenantService;

    /**
     * 创建租户
     */
    @PostMapping
    @RequirePermission(value = {"tenant:create", "tenant:manage"}, description = "创建租户")
    @Operation(summary = "创建租户", description = "注册新租户，同时初始化默认配置")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "租户创建成功"),
            @ApiResponse(responseCode = "400", description = "请求参数错误"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "409", description = "租户编码或邮箱已存在")
    })
    public Result<Tenant> createTenant(@Valid @RequestBody CreateTenantRequest request) {
        log.info("创建租户请求: {}", request.getTenantCode());
        
        try {
            // 将请求DTO转换为实体
            Tenant tenant = new Tenant();
            BeanUtils.copyProperties(request, tenant);
            
            // 创建租户
            Tenant createdTenant = tenantService.createTenant(tenant);
            
            log.info("租户创建成功: ID={}, 编码={}", createdTenant.getId(), createdTenant.getTenantCode());
            return Result.success(createdTenant, "租户创建成功");
            
        } catch (Exception e) {
            log.error("创建租户失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据ID获取租户
     */
    @GetMapping("/{id}")
    @RequirePermission(value = {"tenant:view", "tenant:manage"}, description = "查看租户详情")
    @Operation(summary = "获取租户详情", description = "根据租户ID获取租户详细信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足"),
            @ApiResponse(responseCode = "404", description = "租户不存在")
    })
    public Result<Tenant> getTenantById(@Parameter(description = "租户ID", required = true) @PathVariable Long id) {
        log.info("获取租户: ID={}", id);
        
        try {
            Tenant tenant = tenantService.getTenantById(id);
            if (tenant == null) {
                return Result.notFound("租户不存在");
            }
            
            return Result.success(tenant);
            
        } catch (Exception e) {
            log.error("获取租户失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据租户编码获取租户
     */
    @GetMapping("/code/{tenantCode}")
    @RequirePermission(value = {"tenant:view", "tenant:manage"}, description = "根据编码查看租户")
    public Result<Tenant> getTenantByCode(@PathVariable String tenantCode) {
        log.info("根据编码获取租户: {}", tenantCode);
        
        try {
            Tenant tenant = tenantService.getTenantByCode(tenantCode);
            if (tenant == null) {
                return Result.notFound("租户不存在");
            }
            
            return Result.success(tenant);
            
        } catch (Exception e) {
            log.error("获取租户失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取所有租户列表
     */
    @GetMapping
    @RequirePermission(value = {"tenant:view", "tenant:manage"}, description = "查看租户列表")
    @Operation(summary = "获取租户列表", description = "获取所有租户列表，支持按状态过滤")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "401", description = "未授权"),
            @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public Result<List<Tenant>> getAllTenants(
            @Parameter(description = "租户状态过滤（1-正常，2-待审核，3-暂停，0-已删除）")
            @RequestParam(required = false) Integer status) {
        log.info("获取租户列表, 状态过滤: {}", status);
        
        try {
            List<Tenant> tenants;
            if (status != null) {
                tenants = tenantService.getTenantsByStatus(status);
            } else {
                tenants = tenantService.getAllTenants();
            }
            
            return Result.success(tenants);
            
        } catch (Exception e) {
            log.error("获取租户列表失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新租户
     */
    @PutMapping("/{id}")
    @RequirePermission(value = {"tenant:update", "tenant:manage"}, description = "更新租户信息")
    public Result<Tenant> updateTenant(@PathVariable Long id, @Valid @RequestBody UpdateTenantRequest request) {
        log.info("更新租户: ID={}", id);
        
        try {
            // 检查ID一致性
            if (!id.equals(request.getId())) {
                return Result.validateError("路径中的ID与请求体中的ID不一致");
            }
            
            // 将请求DTO转换为实体
            Tenant tenant = new Tenant();
            BeanUtils.copyProperties(request, tenant);
            
            // 更新租户
            Tenant updatedTenant = tenantService.updateTenant(tenant);
            
            log.info("租户更新成功: ID={}, 编码={}", updatedTenant.getId(), updatedTenant.getTenantCode());
            return Result.success(updatedTenant, "租户更新成功");
            
        } catch (Exception e) {
            log.error("更新租户失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除租户
     */
    @DeleteMapping("/{id}")
    @RequirePermission(value = {"tenant:delete", "tenant:manage"}, description = "删除租户")
    public Result<Void> deleteTenant(@PathVariable Long id) {
        log.info("删除租户: ID={}", id);
        
        try {
            boolean success = tenantService.deleteTenant(id);
            if (success) {
                return Result.success(null, "租户删除成功");
            } else {
                return Result.error("租户删除失败");
            }
            
        } catch (Exception e) {
            log.error("删除租户失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 激活租户
     */
    @PutMapping("/{id}/activate")
    @RequirePermission(value = {"tenant:update", "tenant:manage"}, description = "激活租户")
    public Result<Void> activateTenant(@PathVariable Long id) {
        log.info("激活租户: ID={}", id);
        
        try {
            boolean success = tenantService.activateTenant(id);
            if (success) {
                return Result.success(null, "租户激活成功");
            } else {
                return Result.error("租户激活失败");
            }
            
        } catch (Exception e) {
            log.error("激活租户失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 暂停租户
     */
    @PutMapping("/{id}/suspend")
    @RequirePermission(value = {"tenant:update", "tenant:manage"}, description = "暂停租户")
    public Result<Void> suspendTenant(@PathVariable Long id) {
        log.info("暂停租户: ID={}", id);
        
        try {
            boolean success = tenantService.suspendTenant(id);
            if (success) {
                return Result.success(null, "租户暂停成功");
            } else {
                return Result.error("租户暂停失败");
            }
            
        } catch (Exception e) {
            log.error("暂停租户失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查租户编码是否存在
     */
    @GetMapping("/exists/code/{tenantCode}")
    public Result<Boolean> existsByTenantCode(@PathVariable String tenantCode) {
        log.debug("检查租户编码是否存在: {}", tenantCode);
        
        try {
            boolean exists = tenantService.existsByTenantCode(tenantCode);
            return Result.success(exists);
            
        } catch (Exception e) {
            log.error("检查租户编码失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 检查邮箱是否已被使用
     */
    @GetMapping("/exists/email/{email}")
    public Result<Boolean> existsByEmail(@PathVariable String email) {
        log.debug("检查邮箱是否已被使用: {}", email);
        
        try {
            boolean exists = tenantService.existsByEmail(email);
            return Result.success(exists);
            
        } catch (Exception e) {
            log.error("检查邮箱失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }
}